<?php

namespace app\service;

use app\model\Article;

class ArticleService
{
    private $article;

    public function __construct()
    {
        $this->article = new Article();
    }

    public function list($params = [])
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];

        if (!empty($params['title'])) {
            $where[] = ['title', 'like', '%' . trim($params['title']) . '%'];
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        if (isset($params['category_id']) && $params['category_id'] !== '') {
            $where[] = ['category_id', '=', $params['category_id']];
        }

        if(!empty($params['type'])){
            if($params['type']=="notice")  $where[] = ['category_id', '=', 1];
        }

        $result = $this->article->with(['category'])->where($where)
            ->order(['sort' => 'desc', 'updated_at'=>'desc','id' => 'desc'])->append(['status_text'])
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        return $result;
    }

    public function save($param)
    {
        if(isset($param['id'])) unset($param['id']);
        return $this->article->allowField(['title','cover', 'content', 'category_id', 'status', 'sort', 'image'])->create($param);
    }

    public function update($id, $param)
    {
        $article = $this->article->find($id);
        return $article->allowField(['title','cover', 'content', 'category_id', 'status', 'sort', 'image'])->save($param);
    }

    public function delete($id)
    {
        return $this->article->destroy($id);
    }

    public function detail($id)
    {
        return $this->article->with(['category'])->find($id);
    }


}
